﻿using FarmSmartSleep.Common.Domain.RBACFile;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using MediatR;

namespace R.FarmSmartSleep.RBAC.API.Apliction.Command.Permissions
{
    /// <summary>
    /// 添加权限角色
    /// </summary>
    public class PermissionRolesCreateHandler:IRequestHandler<PermissionRolesCreateCommon,Result>
    {

        private readonly IBaseRepository<RolesPermissions> rolesPermissionsRep;
        /// <summary>
        /// 添加权限角色
        /// </summary>
        /// <param name="rolesPermissionsRep"></param>
        public PermissionRolesCreateHandler(IBaseRepository<RolesPermissions> rolesPermissionsRep)
        {
             this.rolesPermissionsRep=rolesPermissionsRep;
        }
        /// <summary>
        /// 添加权限角色
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(PermissionRolesCreateCommon request, CancellationToken cancellationToken)
        {
             var result = new Result() { Code = (int)CodeEnum.add};
            try
            {
                var n = new List<RolesPermissions>();
                foreach (var item in request.rolesIds)
                {
                   var rolePermission= new RolesPermissions()
                    {
                        PermissionsId = request.permissionsId,
                        RolesId = item
                    };
                     n.Add(rolePermission);
                }
                if(n==null)
                {
                    result.Messege = "添加失败";
                    return result;
                }
               await rolesPermissionsRep.AddRange(n); 
                result.Code = (int)CodeEnum.success;
                result.Messege = "添加成功";
            }
            catch (Exception)
            {
                result.Messege = "添加异常";
                throw;
            }
            return result;
        }
    }
}
